#![allow(dead_code)]
use serde::{Deserialize, Serialize};
use serde::de::DeserializeOwned;

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(bound(deserialize = "T: DeserializeOwned"))]
#[serde(bound(serialize = "T: Serialize"))]
pub struct PageResult<T> {
    pub code: i32,         // 状态码
    pub msg: String,       // 消息
    pub total: u64,        // 总记录数
    pub rows: Vec<T>,      // 当前页数据
}

impl<T> PageResult<T> {
    // 成功响应 - 带分页数据
    pub fn succeed(rows: Vec<T>, total: u64) -> Self {
        Self {
            code: 200,
            msg: "操作成功".to_string(),
            total,
            rows,
        }
    }

    // 失败响应 - 自定义错误码和消息
    pub fn failed(code: i32, msg: impl Into<String>) -> Self {
        Self {
            code,
            msg: msg.into(),
            total: 0,
            rows: Vec::new(),
        }
    }

    // 常见错误 - 参数错误
    pub fn param_error(msg: impl Into<String>) -> Self {
        Self::failed(400, msg)
    }

    // 常见错误 - 未授权
    pub fn unauthorized(msg: impl Into<String>) -> Self {
        Self::failed(401, msg)
    }

    // 常见错误 - 禁止访问
    pub fn forbidden(msg: impl Into<String>) -> Self {
        Self::failed(403, msg)
    }

    // 常见错误 - 资源不存在
    pub fn not_found(msg: impl Into<String>) -> Self {
        Self::failed(404, msg)
    }

    // 常见错误 - 服务器内部错误
    pub fn internal_error(msg: impl Into<String>) -> Self {
        Self::failed(500, msg)
    }
    pub fn from_result<E: ToString>(result: Result<Vec<T>, E>, total: u64) -> Self {
        match result {
            Ok(rows) => Self::succeed(rows, total),
            Err(err) => Self::failed(500, err.to_string()),
        }
    }

}

// 针对空数据的快捷方法
impl<T> PageResult<T> {
    // 创建空数据的成功响应
    pub fn empty() -> Self {
        Self {
            code: 200,
            msg: "操作成功".to_string(),
            total: 0,
            rows: Vec::new(),
        }
    }
}